<?php

namespace app\merchant_staff\controller\billiard;

use addons\mycurrency\library\Common;
use app\common\controller\MerchantStaff;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\mycurrency\Agent;
use app\common\model\mycurrency\AgentConfig;
use app\common\model\mycurrency\AgentMoneyWithdrawal;
use app\common\model\mycurrency\AgentProfit;
use app\common\model\mycurrency\LeaseOrder;
use app\common\model\mycurrency\MerchantConfig;
use app\common\model\mycurrency\MerchantMoneyWithdrawal;
use app\common\model\mycurrency\MerchantProfit;
use app\common\model\mycurrency\MerchantStore;
use fast\Random;
use think\Config;
use think\Db;
use think\Exception;
use think\Validate;
use app\common\model\mycurrency\MerchantStaff as StaffMoney;

/**
 * 账号接口
 */
class Staff extends MerchantStaff
{
    protected $noNeedLogin = ['login'];
    protected $noNeedRight = '*';

    protected $verificationIdentity = ['login'];//身份验证

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }
    }

    /**
     * 登录
     *
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('账号密码不能为空'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['info' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 账号信息
     */
    public function index()
    {
        $info = [];//基本信息
        $identity = null;//身份： 1 省代 2 市代 3 区县代理 4 业务员 5 门店
        $income_statistics = [];//收益数据统计
        $order_statistics = [];//订单统计

        $staff_id = $this->auth->id;
        $staff = StaffMoney::where(['id' => $staff_id])->find();

        //今日时间戳
        $todayTime =  strtotime(date("Y-m-d 00:00:00")).','.strtotime(date("Y-m-d 23:59:59"));

        //本周开始 及本周 结束时间戳
        $startTimestamp = strtotime("this week Monday");
        $endTimestamp = strtotime("this week Sunday") + 86400 - 1;
        $circumTime = $startTimestamp.','.$endTimestamp;

        //本月开始 及本月 结束时间戳
        $firstDayOfMonth = strtotime(date('Y-m-01 00:00:00'));
        $lastDayOfMonth = strtotime(date('Y-m-t 23:59:59'));
        $themoonTime = $firstDayOfMonth . ',' . $lastDayOfMonth;


        if ($staff->identity == StaffMoney::IDENTITY_DAILI || $staff->identity == StaffMoney::IDENTITY_YEWU){//身份:1=代理,2=业务员
            $agent_id = $staff->identity == StaffMoney::IDENTITY_DAILI ? $staff->agent_id : $staff->business_agent_id;
            $agent = Agent::where(['id' => $agent_id])->find();


            //基本信息
            $info['id'] = $agent->id;
            $info['name'] = $agent->name;
            $info['fullname'] = $agent->fullname;
            $info['phone'] = $agent->phone;
            $info['money'] = $agent->money;

            $info['bank_number'] = $agent->bank_number;
            $info['bank_opening'] = $agent->bank_opening;
            $info['bank_account'] = $agent->bank_account;
            $info['wechat_code_image'] = $agent->wechat_code_image;
            $info['alipay_code_image'] = $agent->alipay_code_image;
            $info['wechat_code_image_http'] = $info['wechat_code_image'] == null ? '' : Common::GetHost() . $agent['wechat_code_image'];
            $info['alipay_code_image_http'] = $info['alipay_code_image'] == null ? '' : Common::GetHost() . $agent['alipay_code_image'];

            //身份
            if($agent->role_type == Agent::ROLE_TYPE_DAILI){//区域代理
                switch ($agent->level) {
                    case Agent::LEVEL_SHENG://省代理
                        $identity = 1;
                        break;
                    case Agent::LEVEL_SHI://市代理
                        $identity = 2;
                        break;
                    case Agent::LEVEL_QUXIAN://区县代理
                        $identity = 3;
                        break;
                    default:
                        break;
                }
            }elseif ($agent->role_type == Agent::ROLE_TYPE_YEWUYUAN){//业务员
                $identity = 4;
            }

            //收益统计
            //默认查询条件
            $where = ['agent_id' => $agent->id,'deletetime' => null];
            //收益数据
            $income_statistics = [
                'profit_total' => number_format(AgentProfit::where($where)->sum('actual_income'),2),//总计收益
                'profit_canreflect' => $agent['money'],//可提现收益
                'profit_today' => number_format(AgentProfit::where($where)->where(['createtime' => ['between',$todayTime]])->sum('actual_income'),2),//今日收益
                'profit_thisweek' => number_format(AgentProfit::where($where)->where(['createtime' => ['between',$circumTime]])->sum('actual_income'),2),//本周收益
                'profit_thismonth'=> number_format(AgentProfit::where($where)->where(['createtime' => ['between',$themoonTime]])->sum('actual_income'),2),//本月收益
            ];

            //订单统计
            $where = ['agent_id' => $agent->id,'deletetime' => null,'use_status' => ['<>',LeaseOrder::USE_STATUS_YIQUXIAO]];
            $order_statistics = [
                'profit_total' => LeaseOrder::where($where)->count(),//总订单
                'profit_today' => LeaseOrder::where($where)->where(['createtime' => ['between',$todayTime]])->count(),//今日订单
                'profit_thisweek' => LeaseOrder::where($where)->where(['createtime' => ['between',$circumTime]])->count(),//本周订单
                'profit_thismonth'=> LeaseOrder::where($where)->where(['createtime' => ['between',$themoonTime]])->count(),//本月订单
            ];
        }
        elseif ($staff->identity == StaffMoney::IDENTITY_MENDIAN){//身份:3=门店
            $store = MerchantStore::get($staff->store_id);

            //基本信息
            $info['id'] = $store->id;
            $info['name'] = $store->store_name;
            $info['fullname'] = $store->fullname;
            $info['phone'] = $store->phone;
            $info['money'] = $store->money;

            $info['bank_number'] = $store->bank_number;
            $info['bank_opening'] = $store->bank_opening;
            $info['bank_account'] = $store->bank_account;
            $info['wechat_code_image'] = $store->wechat_code_image;
            $info['alipay_code_image'] = $store->alipay_code_image;
            $info['wechat_code_image_http'] = $store['wechat_code_image'] == null ? '' : Common::GetHost() . $store['wechat_code_image'];
            $info['alipay_code_image_http'] = $store['alipay_code_image'] == null ? '' : Common::GetHost() . $store['alipay_code_image'];
            $info['management_type'] = $store['management_type'];
            //身份
            $identity = 5;

            //收益统计
            //默认查询条件
            $where = ['change_type' => MerchantProfit::CHANGE_TYPE_MENDIAN, 'store_id' => $store->id, 'deletetime' => null];
            //收益数据
            $income_statistics = [
                'profit_total' => number_format(MerchantProfit::where($where)->sum('actual_income'),2),//总计收益
                'profit_canreflect' => $store['money'],//可提现收益
                'profit_today' => number_format(MerchantProfit::where($where)->where(['createtime' => ['between',$todayTime]])->sum('actual_income'),2),//今日收益
                'profit_thisweek' =>number_format(MerchantProfit::where($where)->where(['createtime' => ['between',$circumTime]])->sum('actual_income'),2),//本周收益
                'profit_thismonth'=> number_format(MerchantProfit::where($where)->where(['createtime' => ['between',$themoonTime]])->sum('actual_income'),2),//本月收益
            ];

            //订单统计
            $where = ['store_id' => $store->id,'deletetime' => null,'use_status' => ['<>',LeaseOrder::USE_STATUS_YIQUXIAO]];
            $order_statistics = [
                'profit_total' => LeaseOrder::where($where)->count(),//总订单
                'profit_today' => LeaseOrder::where($where)->where(['createtime' => ['between',$todayTime]])->count(),//今日订单
                'profit_thisweek' => LeaseOrder::where($where)->where(['createtime' => ['between',$circumTime]])->count(),//本周订单
                'profit_thismonth'=> LeaseOrder::where($where)->where(['createtime' => ['between',$themoonTime]])->count(),//本月订单
            ];
        }
        $info['avatar'] = Common::GetHost() . \app\common\model\Config::where(['name' => 'user_default_headportrait'])->value('value');
        $this->success('',[
            'info' => $info,
            'identity' => $identity,
            'income_statistics' => $income_statistics,
            'order_statistics' => $order_statistics,
        ]);
    }


    /**
     * 收益提现 - 查询提现配置信息
    */
    public function carryConfig(){
        if ($this->staff->identity == StaffMoney::IDENTITY_DAILI || $this->staff->identity == StaffMoney::IDENTITY_YEWU){
            $data = AgentConfig::where(['id' => 1])->field('witserpro,minwit_amount,explain_content')->find();
        }elseif ($this->staff->identity == StaffMoney::IDENTITY_MENDIAN){
            $data = MerchantConfig::where(['id' => 1])->field('witserpro,minwit_amount,explain_content')->find();
        }
        $this->success('加载成功',$data);
    }

    /**
     * 修改收款信息
     */
    public function carryAccountUpdate(){
        $param = $this->request->param();
        $data = [
            'bank_number' => $param['bank_number'],
            'bank_opening' => $param['bank_opening'],
            'bank_account' => $param['bank_account'],
            'wechat_code_image' => $param['wechat_code_image'],
            'alipay_code_image' => $param['alipay_code_image'],
        ];
        if ($this->identity == 1){//代理商或者业务员
            $res = Agent::where(['id' => $this->agent_id])->update($data);
        }elseif ($this->identity == 2){//门店
            $res = MerchantStore::where(['id' => $this->store_id])->update($data);
        }
        if (!$res){
            $this->error('修改失败');
        }
        $this->success('修改成功');
    }

    /**
     * 发起提现
     */
    public function carryWithdrawal(){
        $param = $this->request->param();
        $rule = [
            ['money', 'require|>:0', '提现金额不能为空|提现金额必须是大于0的数字'],
            ['payment_mode', 'require', '提现方式不能为空'],
        ];
        $check = $this->validate($param, $rule);
        if ($check !== true) {
            $this->error($check);
        }
        if($param['payment_mode'] == AgentMoneyWithdrawal::PAYMENT_MODE_XIANXIA){//打款方式为线下打款
            if (!array_key_exists('bank_number',$param) || !$param['bank_number'] ||
                !array_key_exists('bank_opening',$param) || !$param['bank_opening'] ||
                !array_key_exists('bank_account',$param) ||!$param['bank_account']){
                throw new Exception('银行卡信息不完善');
                return false;
            }
        }elseif ($param['payment_mode']  == AgentMoneyWithdrawal::PAYMENT_MODE_WEIXINSHOUKUANMA){//提现方式:4=微信收款码收款
            if (!array_key_exists('wechat_code_image',$param) ||!$param['wechat_code_image']){
                throw new Exception('微信收款码不能为空');
                return false;
            }
        }elseif ($param['payment_mode']  == AgentMoneyWithdrawal::PAYMENT_MODE_ZHIFUBAOSHOUKUANMA){//提现方式:5=支付宝收款码收款
            if (!array_key_exists('alipay_code_image',$param) ||!$param['alipay_code_image']){
                throw new Exception('支付宝收款吗不能为空');
                return false;
            }
        }
        $receive = [
            'bank_number' => $param['bank_number'],
            'bank_opening' => $param['bank_opening'],
            'bank_account' => $param['bank_account'],
            'wechat_code_image' => $param['wechat_code_image'],
            'alipay_code_image' => $param['alipay_code_image'],
        ];
        Db::startTrans();
        try {
            if ($this->identity == 1){//代理商或者业务员
                AgentMoneyWithdrawal::withdrawal(
                    $this->agent_id,
                    $param['money'],
                    $param['payment_mode'],
                    $receive,$param['explain']
                );
                //更新收款信息
                $agent_update = [];
                if($param['payment_mode'] == AgentMoneyWithdrawal::PAYMENT_MODE_XIANXIA){//打款方式为线下打款
                    $agent_update['bank_number'] = $param['bank_number'];
                    $agent_update['bank_opening'] = $param['bank_opening'];
                    $agent_update['bank_account'] = $param['bank_account'];
                }elseif ($param['payment_mode']  == AgentMoneyWithdrawal::PAYMENT_MODE_WEIXINSHOUKUANMA){//提现方式:4=微信收款码收款
                    $agent_update['wechat_code_image'] = $param['wechat_code_image'];
                }elseif ($param['payment_mode']  == AgentMoneyWithdrawal::PAYMENT_MODE_ZHIFUBAOSHOUKUANMA){//提现方式:5=支付宝收款码收款
                    $agent_update['alipay_code_image'] = $param['alipay_code_image'];
                }
                Agent::where(['id' => $this->agent_id])->update($agent_update);
            }elseif ($this->identity == 2){//门店
                MerchantMoneyWithdrawal::withdrawal(
                    MerchantMoneyWithdrawal::CHANGE_TYPE_STORE,
                    null,
                    $this->store_id,
                    $param['money'],
                    $param['payment_mode'],
                    $receive,$param['explain']
                );
                //更新收款信息
                $store_update = [];
                if($param['payment_mode'] == AgentMoneyWithdrawal::PAYMENT_MODE_XIANXIA){//打款方式为线下打款
                    $store_update['bank_number'] = $param['bank_number'];
                    $store_update['bank_opening'] = $param['bank_opening'];
                    $store_update['bank_account'] = $param['bank_account'];
                }elseif ($param['payment_mode']  == AgentMoneyWithdrawal::PAYMENT_MODE_WEIXINSHOUKUANMA){//提现方式:4=微信收款码收款
                    $store_update['wechat_code_image'] = $param['wechat_code_image'];
                }elseif ($param['payment_mode']  == AgentMoneyWithdrawal::PAYMENT_MODE_ZHIFUBAOSHOUKUANMA){//提现方式:5=支付宝收款码收款
                    $store_update['alipay_code_image'] = $param['alipay_code_image'];
                }
                MerchantStore::where(['id' => $this->store_id])->update($store_update);
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('申请提现成功');
    }

    /**
     * 提现明细
     */
    public function withdrawalLog(){
        $params = $this->request->param();
        $rule = [
            ['page', 'require', '页码不能为空'],
            ['pageSize', 'require', '每页查询条数不能为空'],
        ];
        $check = $this->validate($params, $rule);
        if ($check !== true) {
            $this->error($check);
        }

        if ($this->identity == 1){//代理商或者业务员
            $money = new AgentMoneyWithdrawal();
            $where = [
                'agent_id' => $this->agent_id,
                'deletetime' => null,
            ];
        }elseif ($this->identity == 2){//门店
            $money = new MerchantMoneyWithdrawal();
            $where = [
                'store_id' => $this->store_id,
                'deletetime' => null,
            ];
        }

        $list = $money::where($where)
            ->limit(($params['page'] - 1) * $params['pageSize'], $params['pageSize'])
            ->order('id desc')
            ->field('*')
            ->select();
        foreach($list as $k => $v){

        }
        $num = $money::where($where)->count();
        if ($num > $params['page'] * $params['pageSize']) {
            $nextpage = true;
        } else {
            $nextpage = false;
        }
        $this->success('获取成功', ['list' => $list, 'nextpage' => $nextpage]);
    }

    /**
     * 收益明细
    */
    public function profitList(){
        $params = $this->request->param();
        $rule = [
            ['page', 'require', '页码不能为空'],
            ['pageSize', 'require', '每页查询条数不能为空'],
        ];
        $check = $this->validate($params, $rule);
        if ($check !== true) {
            $this->error($check);
        }

        if ($this->identity == 1){//代理商或者业务员
            $money = new AgentProfit();
            $where = [
                'agent_id' => $this->agent_id,
                'deletetime' => null,
            ];
        }elseif ($this->identity == 2){//门店
            $money = new MerchantProfit();
            $where = [
                'store_id' => $this->store_id,
                'deletetime' => null,
            ];
        }

        $list = $money::where($where)
            ->limit(($params['page'] - 1) * $params['pageSize'], $params['pageSize'])
            ->order('id desc')
            ->field('*')
            ->select();
        foreach($list as $k => $v){

        }
        $num = $money::where($where)->count();
        if ($num > $params['page'] * $params['pageSize']) {
            $nextpage = true;
        } else {
            $nextpage = false;
        }
        $this->success('获取成功', ['list' => $list, 'nextpage' => $nextpage]);
    }


    /**
     * 门店收益排行
    */
    public function profitRanking(){
        $params = $this->request->param();
        $rule = [
            ['page', 'require', '页码不能为空'],
            ['pageSize', 'require', '每页查询条数不能为空'],
        ];
        $check = $this->validate($params, $rule);
        if ($check !== true) {
            $this->error($check);
        }
        $where = [
            'deletetime' => null,
        ];

        if ($params['timeslot_type'] != null && $params['timeslot_type'] != 0){
            if ($params['timeslot_type'] == 1){//今日
                //今日时间戳
                $timeslot =  strtotime(date("Y-m-d 00:00:00")).','.strtotime(date("Y-m-d 23:59:59"));
            }elseif($params['timeslot_type'] == 2){//本周
                //本周开始 及本周 结束时间戳
                $startTimestamp = strtotime("this week Monday");
                $endTimestamp = strtotime("this week Sunday") + 86400 - 1;
                $timeslot = $startTimestamp.','.$endTimestamp;
            }elseif($params['timeslot_type'] == 3){//本月
                //本月开始 及本月 结束时间戳
                $firstDayOfMonth = strtotime(date('Y-m-01 00:00:00'));
                $lastDayOfMonth = strtotime(date('Y-m-t 23:59:59'));
                $timeslot = $firstDayOfMonth . ',' . $lastDayOfMonth;
            }
            $where['createtime'] = ['between',$timeslot];
        }
        $staff_id = $this->auth->id;
        $staff = StaffMoney::where(['id' => $staff_id])->find();
        $agent_id = $staff->identity == StaffMoney::IDENTITY_DAILI ? $staff->agent_id : $staff->business_agent_id;
        $store_ids = Agent::getJuniorStoreIds($agent_id);//获取下级门店id
        if($store_ids){
            $where['store_id'] = ['in',$store_ids];
        }
        $list = MerchantProfit::with(['store' =>function($query){
                $query->field('id,store_name,status,dorrhead_image');
            }])
            ->where($where)
            ->field('store_id,sum(actual_income) as total_income')
            ->group('store_id')
            ->limit(($params['page'] - 1) * $params['pageSize'], $params['pageSize'])
            ->order('total_income desc')
            ->select();
        $num = MerchantProfit::where($where)->count();
        if ($num > $params['page'] * $params['pageSize']) {
            $nextpage = true;
        } else {
            $nextpage = false;
        }
        $this->success('获取成功', ['list' => $list, 'nextpage' => $nextpage]);
    }

    /**
     * 门店信息修改
    */
    public function storeUpdate(){
        $params = $this->request->param();
        $rule = [
            ['store_id', 'require', '门店id不能为空'],
            ['store_name', 'require', '门店名称不能为空'],
            ['dorrhead_image', 'require', '门头照片不能为空'],
            ['phone', 'require', '联系电话不能为空'],
        ];
        $check = $this->validate($params, $rule);
        if ($check !== true) {
            $this->error($check);
        }
        $store = MerchantStore::get($params['store_id']);
        if(!$store){
            $this->error('门店不存在');
        }
        $store->store_name = $params['store_name'];
        $store->dorrhead_image = $params['dorrhead_image'];
        $store->phone = $params['phone'];
        $store->save();
        $this->success('修改成功');
    }



}
